package breakout2014;

import com.jme3.math.Vector3f;


// Utility class for calculating collisions of line segments and angles
public class LineSegmentIntersection {
    private Vector3f sSeg1;
    private Vector3f eSeg1;
    private Vector3f sSeg2;
    private Vector3f eSeg2;
    private Vector3f dirSeg1;
    private Vector3f dirSeg2;
    private Vector3f intersection;    
    float magSeg1;
    float magSeg2;

    public LineSegmentIntersection(Vector3f sSegment1, Vector3f eSegment1, Vector3f sSegment2, Vector3f eSegment2) {
        sSeg1 = sSegment1;
        eSeg1 = eSegment1;
        sSeg2 = sSegment2;
        eSeg2 = eSegment2;
        dirSeg1 = eSeg1.subtract(sSeg1);
        dirSeg2 = eSeg2.subtract(sSeg2);
                
        magSeg1 = (dirSeg2.x*(sSeg2.y-sSeg1.y)-dirSeg2.y*(sSeg2.x-sSeg1.x))/(-dirSeg1.x*dirSeg2.y+dirSeg2.x*dirSeg1.y);
        magSeg2 = (magSeg1*dirSeg1.x-sSeg2.x+sSeg1.x)/(dirSeg2.x);
        intersection = sSeg1.add(dirSeg1.mult(magSeg1));

        
        //System.out.println("sSeg1: " + sSeg1);
        //System.out.println("eSeg1: " + eSeg1);
        //System.out.println("sSeg2: " + sSeg2);
        //System.out.println("eSeg2: " + eSeg2);
        //System.out.println("dirSeg1: " + dirSeg1);
        //System.out.println("dirSeg2: " + dirSeg2);
        //System.out.println("magSeg1: " + magSeg1);
        //System.out.println("magSeg2: " + magSeg2);
        //System.out.println("intersection: " + intersection);
    
    }
    
    public boolean isIntersected() {
        if ( (magSeg1 <= 1) && (magSeg1 > 0) &&(magSeg2 <= 1) &&(magSeg2 > 0))
            return true;
        return false;
    }
    
    public Vector3f getIntersection() {
        return intersection;
    }
    
    public Vector3f getOrtho(Vector3f in){
         return new Vector3f(-in.y, in.x, 0);
     }
    public float dot(Vector3f v1, Vector3f v2){
        return v1.x*v2.x+v1.y*v2.y;
     }
    
    public Vector3f reflectS1AtS2() {
        Vector3f reflectVector;
        Vector3f orthoSeg2 = getOrtho(dirSeg2.normalize());
        float orthoComp = dot(orthoSeg2, dirSeg1);
        reflectVector = dirSeg1.add(orthoSeg2.mult(-orthoComp*2));
        //System.out.println("dirSeg1: " + dirSeg1);                
        //System.out.println("dirSeg2: " + dirSeg2.normalize());                
        //System.out.println("reflected vector: " + reflectVector);
        return reflectVector;
    }
    
}
